package org.sample.commons.code;

import org.apache.commons.lang3.StringUtils;
import org.sample.commons.lang.StrUtils;

import java.lang.reflect.Method;
import java.util.Set;
import java.util.TreeSet;

public class SQLGenerator {

    public static String find(Class<?> clazz, String propName) {
        Method[] methods = clazz.getDeclaredMethods();
        Set<String> names = new TreeSet<>();
        for (Method m : methods)
            names.add(m.getName());


        String className = clazz.getName();
        String tableName = StrUtils.toUnderline(clazz.getSimpleName());
        StringBuilder select = new StringBuilder();
        select.append("<select id=\"find\" parameterType=\"").append(className);
        select.append("\" resultType=\"").append(className);
        select.append("\">\n");
        select.append("select \n");
        StringBuilder where = new StringBuilder();

        for (String name : names) {
            if (name.startsWith("get") && !name.equals("getClass")) {
                name = name.replace("get", "");
                name = StringUtils.uncapitalize(name);
                String column = StrUtils.toUnderline(name);
                select.append("t.").append(column).append(", ");

                if (column.endsWith("time"))
                    continue;
                where.append("<if test=\"").append(propName).append(name).append(" != null\">");
                where.append("and t.").append(column).append(" = #{").append(propName).append("").append(name).append("}");
                where.append("</if>\n");
            }
        }

        select.deleteCharAt(select.length() - 2);
        select.append("\nfrom ").append(tableName).append(" t\n");
        select.append("<where>\n").append(where).append("</where>");
        select.append("\n</select>");
        return select.toString();
    }

}